package com.ruoyi.legal.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.ResponseModel;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.Pages;
import com.ruoyi.common.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.legal.domain.Letter;
import com.ruoyi.legal.service.ILetterService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 介绍信Controller
 *
 * @author xwj
 * @date 2025-05-08
 */
@RestController
@RequestMapping("/legal/letter")
@Api(tags = "介绍信")
public class LetterController extends BaseController {
    @Autowired
    private ILetterService letterService;
    @Autowired
    private ResourceLoader resourceLoader;
    /**
     * 查询介绍信列表
     */
    @PostMapping("/list")
    @ApiOperation("分页查询")
    public TableDataInfo list(@RequestBody Letter letter) {
        startPage();
        letter.setCreateId(getUserId()); // 只能看自己
        List<Letter> list = letterService.selectLetterList(letter);
        return getDataTable(list);
    }

    @PostMapping("/listManager")
    @ApiOperation("分页查询")
    public TableDataInfo listManager(@RequestBody Letter letter) {
        startPage();
        List<Letter> list = letterService.selectLetterList(letter);
        return getDataTable(list);
    }

    @PostMapping("/listAll")
    @ApiOperation("不分页查询")
    public AjaxResult listAll(@RequestBody Letter letter) {
        startOrderBy();
        letter.setCreateId(getUserId()); // 只能看自己
        List<Letter> list = letterService.selectLetterList(letter);
        return success(list);
    }

    @PostMapping("/listManagerAll")
    @ApiOperation("不分页查询")
    public AjaxResult listManagerAll(@RequestBody Letter letter) {
        startOrderBy();
        List<Letter> list = letterService.selectLetterList(letter);
        return success(list);
    }

    @GetMapping("/getSerialNo")
    @ApiOperation("获取序号")
    public AjaxResult getSerialNo(String year) {
        String no = letterService.getNextSerialNo(year);
        return AjaxResult.success("", no);
    }

    /**
     * 导出介绍信列表
     */
    @Log(title = "介绍信", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出")
    public void export(HttpServletResponse response, Letter letter) {
        List<Letter> list = letterService.selectLetterList(letter);
        ExcelUtil<Letter> util = new ExcelUtil<Letter>(Letter.class);
        util.exportExcel(response, list, "介绍信数据");
    }


    @Anonymous
    @GetMapping("/exportPdf")
    @ApiOperation("导出-pdf")
    public void exportPdf(HttpServletResponse response, Long id) throws IOException, DocumentException {
        System.out.println("id:" + id);
        Resource resource = resourceLoader.getResource("classpath:static/letter-template.pdf");
        System.out.println("resource:" + resource.getURL().getPath());


        Map<String, String> data = new HashMap<>();

        Letter letter = letterService.getById(id);
        String fileName = "介绍信";
        if(letter != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String year = "";
            String month = "";
            String day = "";

            String content = letter.getContent();
            String content1 = "";
            String content2 = "";
            String content3 = "";

            if(letter.getApplyDate() != null) {
                String ymd = dateFormat.format(letter.getApplyDate());
                year = ymd.substring(0,4);
                month = ymd.substring(5, 7);
                day = ymd.substring(8,10);
            }

            if(!StrUtil.isEmpty(content)) {
                content1 = StrUtil.sub(content, 0, 22);
                content2 = StrUtil.sub(content, 22, 52);
                content3 = StrUtil.sub(content, 52, 72);
            }


            fileName += "_" + letter.getUnitName();
            String peopleNum = letter.getPeopleNum() + "";
            String validDay = letter.getValidDay() + "";

            data.put("serialNo", letter.getSerialNo());
            data.put("serialNo2", letter.getSerialNo());
            data.put("unitName", letter.getUnitName());
            data.put("unitName2", letter.getUnitName());
            data.put("userName", letter.getUserName());
            data.put("userName2", letter.getUserName());
            data.put("peopleNum", peopleNum);
            data.put("peopleNum2", peopleNum);
            data.put("validDay", validDay);
            data.put("validDay2", validDay);

            data.put("year", year);
            data.put("year2", year);
            data.put("month", month);
            data.put("month2", month);
            data.put("day", day);
            data.put("day2", day);

            data.put("content1", content1);
            data.put("content2", content2);
            data.put("content3", content3);
            data.put("content4", content1);
        }

        PdfReader reader = new PdfReader(resource.getInputStream());
        ByteArrayOutputStream bos;
        OutputStream out = null;

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "inline;fileName=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));

        try {
            out = new BufferedOutputStream(response.getOutputStream());
            bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper pdfStamper = new PdfStamper(reader, bos);

            /* 使用中文字体 */
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(baseFont);

            AcroFields fields = pdfStamper.getAcroFields();
            fields.setSubstitutionFonts(fontList);

            List<String> keys = new ArrayList<String>();
            Map<String, AcroFields.Item> formFields = fields.getFields();

            for (String key : data.keySet()) {
                if (formFields.containsKey(key)) {
                    String value = data.get(key);
                    fields.setFieldProperty(key, "textsize", 15f, null);

                    fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的

                    keys.add(key);
                }
            }

            Iterator<String> itemsKey = formFields.keySet().iterator();
            while (itemsKey.hasNext()) {
                String itemKey = itemsKey.next();
                if (!keys.contains(itemKey)) {
                    fields.setField(itemKey, " ");
                }
            }

            /* 必须要调用这个，否则文档不会生成的  如果为false那么生成的PDF文件还能编辑，一定要设为true*/
            pdfStamper.setFormFlattening(true);
            pdfStamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                out.close();
            }
        }

    }

    /**
     * 获取介绍信详细信息
     */
    @GetMapping(value = "/info/{id}")
    @ApiOperation("详情")
    public AjaxResult info(@PathVariable("id") Long id) {
        return success(letterService.selectLetterById(id));
    }

    /**
     * 新增介绍信
     */
    @Log(title = "介绍信", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    @ApiOperation("新增")
    public AjaxResult save(@RequestBody Letter letter) {
        SysUser user = getLoginUser().getUser();
        if (letter.getId() == null) {
            letter.setCreateId(user.getUserId());
            letter.setCreateTime(DateUtils.getNowDate());
            letter.setCreateBy(user.getNickName());
            letterService.insertLetter(letter);
        } else {
            letter.setUpdateId(user.getUserId());
            letter.setUpdateTime(DateUtils.getNowDate());
            letter.setUpdateBy(user.getNickName());
            letterService.updateLetter(letter);
        }

        return success(letter);
    }

    /**
     * 修改介绍信
     */
    @Log(title = "介绍信", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ApiOperation("修改")
    public AjaxResult update(@RequestBody Letter letter) {
        SysUser user = getLoginUser().getUser();
        letter.setUpdateId(user.getUserId());
        letter.setUpdateTime(DateUtils.getNowDate());
        letter.setUpdateBy(user.getNickName());
        return success(letterService.updateLetter(letter));
    }

    /**
     * 删除介绍信
     */
    @Log(title = "介绍信", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除或批量删除")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(letterService.deleteLetterByIds(ids));
    }

    @Log(title = "介绍信", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ApiOperation("条件删除")
    public ResponseModel delete(@RequestBody Letter letter) {
        int num = letterService.delete(letter);
        return ResponseModel.of(num);
    }

    @PostMapping("/queryPage")
    @ApiOperation("分页查询-mp")
    public ResponseModel<Pages<Letter>> queryPage(@RequestBody Letter letter) {
        Pages<Letter> page = letterService.queryPage(letter);
        return ResponseModel.of(page);
    }
}
